
<template>
    <rx-layout>
      <div slot="left" width="300">
        <div class="rx-vue-tree-box">
          <div style="text-align: right;">
            <a-button type="primary" @click="expandAll" size="small">展开</a-button>
            <a-button type="primary" @click="collapseAll" size="small">收起</a-button>
          </div>
          <rx-vue-tree
              :tree-data="treeData"
              :show-edit="true"
              label="name"
              field="id"
              @rowClick="handSelect"
              :tree-icon="treeIcon"
              :foldPeerNode="false"
              :expandedKeys="expandedKeys"
              :onlyChildNode="true"
              :showCheckbox="false"
              :iconStyle="{fontSize:'13px',backgroundColor:'transparent',color:'#333'}"
          >
            <div slot="edit" slot-scope="{tree,data}">
              <div class="btn" v-if="tree.type!='file'" @click="addNode(tree,'directory')"><a-icon type="plus" />新建目录</div>
              <div class="btn" v-if="tree.type!='file'" @click="addNode(tree,'file')"><a-icon type="plus" />新建文件</div>
              <div class="btn" v-if="tree.id != '0'" @click="editNode(tree)"><a-icon type="edit" />编辑{{getByName(tree.type)}}</div>
              <div class="btn del" v-if="tree.id != '0'" @click="deleteNode(tree,data)"><a-icon type="delete" />删除{{getByName(tree.type)}}</div>
            </div>
          </rx-vue-tree>
        </div>
      </div>
      <div slot="center">
        <rx-monaco-editor
            v-if="curTree"
            ref="content"
            v-model="content"
            language="java"
            :showFullScreen="false"
            style="height:99%;"
        >
          <template v-slot:monacoeditor>
            <div>
              <a-dropdown>
                <a-menu slot="overlay">
                  <template v-for="(item,index) in variableProjectAry">
                    <a-menu-item :key="item.value" @click="insertScript(item,'project')"> {{item.label}} </a-menu-item>
                  </template>
                </a-menu>
                <a-button style="margin-right: 8px">插入项目变量
                  <a-icon type="down"/>
                </a-button>
              </a-dropdown>
              <a-dropdown>
                <a-menu slot="overlay">
                  <template v-for="(item,index) in variableGlobalAry">
                    <a-menu-item :key="item.value" @click="insertScript(item,'vars')"> {{item.label}} </a-menu-item>
                  </template>
                </a-menu>
                <a-button style="margin-right: 8px">插入全局变量
                  <a-icon type="down"/>
                </a-button>
              </a-dropdown>
              <a-button type="primary" @click="saveContent()">保存</a-button>
            </div>
          </template>
        </rx-monaco-editor>
      </div>
    </rx-layout>
</template>
<script>
    import FormCodegenFilePathApi from '@/api/form/codegen/formCodegenFilePath'
    import FormCodegenVariableApi from "@/api/form/codegen/formCodegenVariable";
    import FormCodegenFilePathEdit from "./FormCodegenFilePathEdit";
    import {RxVueTree,RxMonacoEditor, Util} from "@lowcode/jpaas-common-lib";

    export default {
      name: 'FormCodegenFilePathConfig',
      props:["templateId"],
      components: {
        RxVueTree,
        RxMonacoEditor
      },
      data() {
        return {
          variableProjectAry:[
            {label:"项目变量名",value:"projectVar"},
            {label:"项目别名",value:"projectKey"},
            {label:"项目名称",value:"projectName"},
            {label:"端口号",value:"port"}
          ],
          variableGlobalAry:[],
          expandedKeys:[],
          dataSource:[],
          treeData:[],
          treeIcon:{
            expand:'folder-open',
            collapse:'folder',
            leaf:'file'
          },
          curTree:null,
          content:""
        }
      },
      created() {
        this.init();
      },
      methods: {
        i18n(name,text,key){
          return this.$ti18(name,text,"formCodegenFilePath",key);
        },
        init(){
          var self=this;
          self.initGlobalAry();
          self.treeData.push({id:"0",name:"项目根路径",path:"",parentId:"-1",children:[]});
          self.expandedKeys.push("0");
          FormCodegenFilePathApi.queryList({params:{"Q_DELETED__I_EQ":"0","Q_TEMPLATE_ID__S_EQ":this.templateId},sortField:"TYPE_",sortOrder:"ASC"}).then(res=>{
            if(res.success){
              self.dataSource=res.data;
              let ary=Util.treeData(res.data,"id","parentId");
              let data =Util.deepClone(self.treeData);
              data[0].children = ary ;
              self.treeData = [...data];
            }
          })
        },
        initGlobalAry(){
          var self=this;
          FormCodegenVariableApi.queryList({params:{"Q_ENABLED__S_EQ":"YES"}}).then(res=>{
            if(!res || !res.data){
              return;
            }
            self.variableGlobalAry=res.data.map(item=>{
              return {value:item.name,label:item.desc};
            });
          })
        },
        insertScript(item,alias){
          var script="${"+alias+"."+item.value+"}";
          this.$refs.content.insertContent(script);
        },
        handSelect(tree) {
          if(tree.type!="file" || (this.curTree && this.curTree.id==tree.id)){
            return;
          }
          var self=this;
          //切换文件,自动保存
          this.saveContent(function(){
            self.curTree=tree;
            self.content=tree.content || "";
          });
          
        },
        saveContent(callback) {
          if (callback) {
            if (!this.curTree ||
                this.curTree.content == this.content) {
              callback();
              return;
            }
          }
          this.curTree.content=this.content;
          FormCodegenFilePathApi.save(this.curTree).then(res=>{
            if(callback){
              callback();
            }
          });
        },
        collapseAll() {
          this.expandedKeys.length=0;
          this.expandedKeys.push("0");
        },
        expandAll() {
          this.expandedKeys.length=0;
          this.expandedKeys.push("0");
          for (var i = 0; i < this.dataSource.length; i++) {
            this.expandedKeys.push(this.dataSource[i]["id"])
          }
        },
        addNode(tree,type) {
          let data = {
            type:type,
            templateId:this.templateId,
            parentId:tree.id,
            parentPath:tree.path
          }
          let name=this.getByName(type);
          this.handClick(data, "添加"+name, "addChild",tree);
        },
        editNode(tree) {
          let {type}=tree;
          let name=this.getByName(type);
          this.handClick(tree, "编辑"+name, "edit");
        },
        handClick(data, title, operator,parentData) {
          var conf = {
            curVm: this,
            data: {data: data,globalAry:this.variableGlobalAry},
            widthHeight: ['600px', '200px'],
            component: FormCodegenFilePathEdit,
            title: title,
            maxmin:false
          };
          //编辑
          if (data.id) {
            conf.data.pkId = data.id;
          }
          let self_ = this;
          Util.open(conf, async function (action) {
            if (action != "ok") {
              return;
            }
            let row = this.resultData;
            switch (operator) {
              case "edit":
                data.name=row.name;
                self_.treeData = [...self_.treeData];
                break;
              case "addChild":
                if(parentData.hasOwnProperty('children') && Object.prototype.toString.call(parentData.children).indexOf('Array')>-1){
                  parentData.children.push(row)
                }else {
                  parentData['children'] = [row];
                }
                self_.treeData = [...self_.treeData];
                break;
            }
          });
        },
        getByName(type){
          let name="";
          if(type=="file") {
            name = "文件";
          }else if(type=="directory") {
            name = "目录"
          }
          return name;
        },
        deleteNode(tree,parentData) {
          var {id,type} = tree;
          let name=this.getByName(type);
          let self_ = this;
          this.$confirm({
            title: '操作提示',
            content: '您确定需要删除选中的'+name+'吗？',
            okText: '确认',
            zIndex:10000,
            cancelText: '取消',
            onOk() {
              FormCodegenFilePathApi.del({ids:id}).then(res=>{
                if (res.success && res.code == 200) {
                  let index =  parentData.children.findIndex(obj=>obj.id == tree.id);
                  parentData.children.splice(index,1);
                }
              })
            },
            onCancel() {
            }
          })
        },
      }
    }
</script>
<style scoped>
  .rx-vue-tree-box >>> .rx-expand-icon-box .rx-v-tree-icon{
    font-size: 13px!important;
    margin-left: 1px;
  }
  .rx-vue-tree-box >>> .rx-v-tree-icon{
    margin-top: 1px;
  }
  .rx-vue-tree-box >>> .rx-v-tree-icon-box{
    width: 16px;
  }
  .btn i{
    margin-right: 4px;
  }

</style>
